<script setup lang="ts">
import type { CustomDialogInstance } from '@/types'

import VueDraggable from 'vuedraggable'
import type { EfficiencyConfig, SaveEfficiencyParams } from '../type'
import { EFFICIENCY_DATA_TYPE, EFFICIENCY_LOCATION } from '../constant'
import { STORAGE_MODES } from '@/enum/modules/indicator'

defineOptions({
  name: 'BottomSettingPanel',
})

const props = defineProps<{
  equipmentId: number | string
  oldList: EfficiencyConfig[]
}>()

const emit = defineEmits<{
  (e: 'open'): void
  (e: 'close'): void
  (e: 'saveSuccess'): void
}>()

const dialogRef = ref<CustomDialogInstance>()
const modalTitle = computed(() => {
  return `下侧数据设置${list.value.length}/3`
})

const equipmentStore = useEquipmentStore()

const title = ref()
const list = ref<{
  _uuid: string
  dataName: string
  dataValue: string
  dataType: EFFICIENCY_DATA_TYPE
  timeType: STORAGE_MODES
  _timeTypeOptions: { label: string, value: string }[]
}[]>([])

const indicatorList = computed(() => {
  return equipmentStore.indicatorList
})

async function handleAdd() {
  if (list.value.length < 3) {
    list.value.push({
      _uuid: uuid(),
      dataName: '',
      dataValue: '',
      dataType: EFFICIENCY_DATA_TYPE.POINT,
      timeType: STORAGE_MODES.NOW,
      _timeTypeOptions: [],
    })
  }
  else {
    ElMessage.warning('最多添加3个数据')
  }
}
async function handleRemove(item: any) {
  const index = list.value.indexOf(item)
  if (index > -1) {
    list.value.splice(index, 1)
  }
}

async function clickSave(done: () => void) {
  const params: SaveEfficiencyParams = {
    equipmentId: +unref(props.equipmentId),
    location: EFFICIENCY_LOCATION.BOTTOM,
    list: unref(list).map((v) => {
      return {
        equipmentId: +unref(props.equipmentId),
        location: EFFICIENCY_LOCATION.BOTTOM,
        title: unref(title),
        dataName: v.dataName,
        dataValue: v.dataValue,
        dataType: v.dataType,
        timeType: v.timeType,
      }
    }),
  }
  // if (!unref(title)) {
  //   done()
  //   return ElMessage.warning('请输入标题')
  // }
  if (list.value.length === 0) {
    done()
    return ElMessage.warning('请增加数据')
  }
  if (list.value.some(v => v.dataName === '' || v.dataValue === null)) {
    done()
    return ElMessage.warning('请完善数据')
  }
  try {
    await equipmentEfficiencyApi.saveEquipmentEfficiencyConfigData(params)
    ElMessage.success('保存成功')
    done()
    close()
    emit('saveSuccess')
  }
  finally {
    done()
  }
}

function handleChangeDataType(element: any) {
  const target = unref(list).find(v => v._uuid === element._uuid)
  if (target) {
    target.dataValue = ''
    target.timeType = target.dataType === EFFICIENCY_DATA_TYPE.POINT
      ? STORAGE_MODES.NOW
      : (null as any)
  }
}

function getPeriodName(type: STORAGE_MODES) {
  switch (type) {
    case STORAGE_MODES.DAY:
      return '日'
    case STORAGE_MODES.MONTH:
      return '月'
    case STORAGE_MODES.YEAR:
      return '年'
    case STORAGE_MODES.NOW:
      return '实时'
    case STORAGE_MODES.FIFTEEN_MINUTES:
      return '15分钟'
    case STORAGE_MODES.HOUR:
      return '小时'
    default:
      return ''
  }
}

function getPeriodListFromIndicator(indicatorNumber: string) {
  const indicator = unref(indicatorList).find(v => v.indicatorNumber === indicatorNumber)
  if (indicator) {
    const indicatorDataStoreCoreList = indicator?.indicatorDataStoreCoreList ?? []
    return indicatorDataStoreCoreList.map(v => ({
      label: getPeriodName(v.timeType),
      value: v.timeType,
    }))
  }
  return []
}

function handleChangeDataValue(element: any) {
  const target = unref(list).find(v => v._uuid === element._uuid)
  const indicator = unref(indicatorList).find(v => v.indicatorNumber === element.dataValue)
  if (target) {
    const indicatorDataStoreCoreList = indicator?.indicatorDataStoreCoreList ?? []
    target._timeTypeOptions = indicatorDataStoreCoreList.map(v => ({
      label: getPeriodName(v.timeType),
      value: v.timeType,
    }))
    target.timeType = indicatorDataStoreCoreList[0].timeType
  }
}

const loading = ref(false)

async function open() {
  dialogRef.value?.open()
  if (props.equipmentId) {
    try {
      loading.value = true
      await equipmentStore.getIndicatorList(props.equipmentId)
    }
    finally {
      loading.value = false
    }
  }
  emit('open')
}
async function close() {
  dialogRef.value?.close()
  emit('close')
}

watchEffect(() => {
  title.value = unref(props.oldList)[0]?.title ?? ''
  list.value = unref(props.oldList).map(v => ({
    _uuid: uuid(),
    dataName: v.dataName ?? '',
    dataValue: v.dataValue,
    dataType: v.dataType,
    timeType: v.timeType,
    _timeTypeOptions: getPeriodListFromIndicator(v.dataValue),
  }))
})

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    :title="modalTitle"
    width="640px"
    need-saving
    @confirm="clickSave"
  >
    <div class="flex items-center p-3">
      <span v-if="false" class="required flex-shrink-0 opacity-80">标题：</span>
      <ElInput v-if="false" v-model.trim="title" class="!w-1/2" placeholder="请输入标题名称" />
      <ElButton class="ml-auto" type="success" @click="handleAdd">
        新增数据
      </ElButton>
    </div>
    <div v-loading="loading" element-loading-custom-class="global-loading" class="p-3">
      <VueDraggable
        :list="list" item-key="_uuid"
        ghost-class="ghost"
        chosen-class="chosenClass"
      >
        <template #item="{ element }">
          <div class="item move alpha-block mb-3 flex cursor-move items-center">
            <div class="flex-auto">
              <div class="flex items-center border-b border-gray-200 p-3">
                <span class="block w-20 flex-shrink-0 opacity-80">数据名称：</span>
                <ElInput v-model="element.dataName" class="flex-auto" placeholder="请输入参数名称" />
              </div>
              <div class="flex items-center border-b border-gray-200 p-3">
                <span class="block w-20 flex-shrink-0 opacity-80">数据源类型：</span>
                <ElRadioGroup v-model="element.dataType" class="flex-auto" @change="handleChangeDataType(element)">
                  <ElRadio label="点位" :value="EFFICIENCY_DATA_TYPE.POINT" />
                  <ElRadio label="指标" :value="EFFICIENCY_DATA_TYPE.INDICATOR" />
                </ElRadioGroup>
              </div>
              <div v-if="element.dataType === EFFICIENCY_DATA_TYPE.POINT" class="flex items-center border-b border-gray-200 p-3">
                <span class="block w-20 flex-shrink-0 opacity-80">点位：</span>
                <ElInput v-model="element.dataValue" class="flex-auto" placeholder="请输入" />
              </div>
              <div v-else class="flex items-center border-b border-gray-200 p-3">
                <span class="block w-20 flex-shrink-0 opacity-80">指标：</span>
                <ElSelect v-model="element.dataValue" class="flex-auto" placeholder="请选择" @change="handleChangeDataValue(element)">
                  <ElOption v-for="item in indicatorList" :key="item.indicatorNumber" :value="item.indicatorNumber" :label="item.indicatorName" />
                </ElSelect>
              </div>
              <div class="flex items-center border-b border-gray-200 p-3">
                <span class="block w-20 flex-shrink-0 opacity-80">数据周期：</span>
                <ElSelect v-if="element.dataType === EFFICIENCY_DATA_TYPE.INDICATOR" v-model="element.timeType" :disabled="element.dataType === EFFICIENCY_DATA_TYPE.POINT" class="flex-auto" placeholder="请选择">
                  <ElOption v-for="item in element._timeTypeOptions" :key="item.value" v-bind="item" />
                </ElSelect>
                <ElSelect v-else v-model="element.timeType" class="flex-auto" disabled placeholder="请选择">
                  <ElOption key="0m" label="实时" value="0m" />
                </ElSelect>
              </div>
            </div>
            <div class="flex-shrink-0 px-3">
              <ElButton type="danger" @click="handleRemove(element)">
                移除
              </ElButton>
            </div>
          </div>
        </template>
      </VueDraggable>
    </div>
  </CustomDialog>
</template>

<style scopeds>
.required:before {
  content: '*';
  margin-right: 4px;
  color: rgb(254, 107, 107);
}
.chosenClass {
  border: solid 1px rgb(167, 20, 56);
}
</style>
